import api from '../../api';
import { message } from 'antd';
export default {
  namespace: 'userManageNewM',

  state: {
    data: [], // 用户表格数据
    tenantData: [], // 租户列表数据
    organizationData: [], // 机构列表数据
    stationData: [], // 岗位列表数据
    roleData: [], // 角色列表数据
    cpTreeDate: [], // 关联组合数据
    operatorNumber: undefined, // 通道标识
  },
  effects: {
    // 获取用户ID列表
    *getUserList({ payload, callback }, { call, put }) {
      const res = yield call(api.getUserList, payload);
      if (res && res.success == true) {
        let tempArr = [];
        res.data &&
          res.data.forEach((item) => {
            tempArr.push({ title: item.name, value: item.userId });
          });
        callback('success', tempArr);
      } else {
        callback('fail');
        message.error(`获取用户ID列表失败，失败原因：${res?.mesg}`);
        console.error(`获取用户ID列表失败，失败原因：${res?.mesg}`, '接口名称： findAll 接口：portfolio-server/user/findAll');
      }
    },
    // 获取枚举接口
    *getDictionList({ payload, callback }, { call, put }) {
      const response = yield call(api.getDictionary, payload);
      if (response) {
        // 通道标识
        let tempOperatorNumber = [];
        response.OperatorNumber &&
          response.OperatorNumber.length > 0 &&
          response.OperatorNumber.forEach((item) => {
            tempOperatorNumber.push({ title: item.value, value: item.code });
          });
        yield put({
          type: 'save',
          payload: {
            operatorNumber: tempOperatorNumber, // 通道标识
          },
        });
      } else {
        message.error(`获取字典失败，失败原因：`);
        console.error(`获取字典失败，失败原因：`, '接口名称：queryDictByKeys 接口：dict/queryDictByKeys');
      }
    },
    // 获取用户表格数据
    *Search({ payload }, { call, put }) {
      const data = yield call(api.getUserList, payload);
      if (data && data.success) {
        yield put({
          type: 'save',
          payload: {
            data: data.data,
            loading: false,
          },
        });
      } else {
        message.error(`获取用户表格数据失败，失败原因：${data?.mesg}`);
        console.error(`获取用户表格数据失败，失败原因：${data?.mesg}`, '接口名称： findAll 接口：portfolio-server/user/findAll');
      }
    },
    // 查询用户
    *queryOneUser({ payload }, { call, put }) {
      const data = yield call(api.getUserList, payload);
      if (data && data.success) {
        yield put({
          type: 'save',
          payload: {
            data: data.data,
            loading: false,
          },
        });
      } else {
        message.error(`查询用户失败，失败原因：${data?.mesg}`);
        console.error(`查询用户失败，失败原因：${data?.mesg}`, '接口名称： findAll 接口：portfolio-server/user/findAll');
      }
    },

    // 租户列表
    *getTenantList({ payload }, { call, put }) {
      const res = yield call(api.getTenantList, payload);
      if (res && res.code == 0) {
        let tempArr = [];
        res.data.dataSource &&
          res.data.dataSource.map((item) => {
            tempArr.push({ value: item.code, title: item.name, id: item.id });
          });
        yield put({
          type: 'save',
          payload: {
            tenantData: tempArr,
            loading: false,
          },
        });
      } else {
        message.error(`获取租户信息失败，失败原因：${data?.msg}`);
        console.error(`获取租户信息失败，失败原因：${data?.msg}`, '接口名称： page-query 接口：portfolio-server/tenant/page-query');
      }
    },
    // 获取租户信息
    *SearchTenant({ payload, callback }, { call, put }) {
      const res = yield call(api.getTenantList, payload);
      if (res && res.code == 0) {
        let length = res.data?.dataSource?.length ?? 0;
        let unsecuredAutomaticSettlement;
        if (length == 1) {
          unsecuredAutomaticSettlement = res.data.dataSource[0].unsecuredAutomaticSettlement;
        } else if (length > 1) {
          let newDataSource = res.data.dataSource.filter((item) => item.code == payload.search);
          if (newDataSource.length == 1) {
            unsecuredAutomaticSettlement = newDataSource[0].unsecuredAutomaticSettlement;
          }
        }
        callback(unsecuredAutomaticSettlement);
      } else {
        message.error(`获取租户信息失败，失败原因：${data?.msg}`);
        console.error(`获取租户信息失败，失败原因：${data?.msg}`, '接口名称： page-query 接口：portfolio-server/tenant/page-query');
      }
    },
    // 机构列表
    *getOrganizationData({ payload, callback }, { call, put }) {
      const data = yield call(api.userManageNew.getTree, payload);
      if (data && data.success) {
        let tempArr = [];
        tempArr = JSON.parse(JSON.stringify(data.data).replace(/"key"/g, '"id"'));
        yield put({
          type: 'save',
          payload: {
            organizationData: tempArr,
          },
        });
      } else {
        message.error(`获取机构列表失败，失败原因：${data?.mesg}`);
        console.error(`获取机构列表失败，失败原因：${data?.mesg}`, '接口名称： getTree 接口：portfolio-server/institution/getTree');
      }
    },
    // 岗位列表
    *SearchStation({ payload }, { call, put }) {
      const data = yield call(api.userManageNew.SearchStation, payload);
      if (data && data.success) {
        let tempArr = [];
        data.data &&
          data.data.forEach((item) => {
            tempArr.push({ title: item.postName, value: item.id });
          });
        yield put({
          type: 'save',
          payload: {
            stationData: tempArr,
          },
        });
      } else {
        message.error(`获取岗位列表失败，失败原因：${data?.mesg}`);
        console.error(`获取岗位列表失败，失败原因：${data?.mesg}`, '接口名称： condition 接口：portfolio-server/station/condition');
      }
    },
    // 角色列表
    *SearchRole({ payload }, { call, put }) {
      const data = yield call(api.getRoleList, payload);
      if (data && data.success) {
        let tempArr = [];
        data.data &&
          data.data.forEach((item) => {
            tempArr.push({ title: item.roleName, value: item.id });
          });
        yield put({
          type: 'save',
          payload: {
            roleData: tempArr,
          },
        });
      } else {
        message.error(`获取角色列表失败，失败原因：${data?.message}`);
        console.error(`获取角色列表失败，失败原因：${data?.message}`, '接口名称： condition 接口：portfolio-server/role/condition');
      }
    },
    // 删除用户
    *deleteUser({ payload, callback }, { call, put }) {
      const data = yield call(api.userManageNew.deleteUser, payload);
      if (data && data.code == 0) {
        message.success('删除成功！');
        callback('success');
      } else {
        let msg = '删除失败！';
        if (data.code == '-1') msg = `删除失败！`;
        if (data.code == '-11') msg = `该用户有尚未结束的任务，删除失败！`;
        if (data.code == '-12') msg = `用户已被删除！`;
        if (data.code == '-13') msg = `投顾配置选择用户无法删除！`;
        if (data.code == '-14') msg = `当前用户为租户管理员，不可删除！`;
        callback('fail');
        message.error(`删除失败，失败原因：${data?.mesg || data?.msg}`);
        console.error(`删除失败，失败原因：${data?.mesg || data?.msg}`, '接口名称： remove 接口：portfolio-server/user/remove');
      }
    },
    // 关联组合表格数据
    *cpTreeDateAll({ payload, callback }, { call, put }) {
      const data = yield call(api.userManageNew.cpTreeDateAll, payload);
      if (data && data.success) {
        yield put({
          type: 'save',
          payload: {
            cpTreeDate: data.data,
          },
        });
        callback('success', data.data);
      } else {
        message.error(`获取关联组合数据失败，失败原因：${data?.errorMsg}`);
        console.error(`获取关联组合数据失败，失败原因：${data?.errorMsg}`, '接口名称： add-for-setting 接口：portfolio-server/portfolioInfo/add-for-setting');
        callback('fail');
      }
    },
    // 根据用户id获取关联组合数据
    *cpTreeDate({ payload, callback }, { call, put }) {
      const data = yield call(api.userManageNew.cpTreeDate, payload);
      if (data && data.success) {
        yield put({
          type: 'save',
          payload: {
            cpTreeDate: data.data,
          },
        });
        callback('success', data.data);
      } else {
        callback('fail');
        message.error(`根据用户id获取关联组合数据失败，失败原因：${data?.errorMsg}`);
        console.error(`根据用户id获取关联组合数据失败，失败原因：${data?.errorMsg}`, '接口名称： query-for-setting 接口：portfolio-server/portfolioInfo/query-for-setting');
      }
    },
    // 新增或编辑用户
    *saveTable({ payload, callback }, { call, put }) {
      const data = yield call(api.userManageNew.saveTable, payload);
      if (data && data.code == 0) {
        message.success(data.msg || '操作成功');
        callback('success');
      } else {
        let msg = '操作失败！';
        if (data.code == '-1') msg = `操作失败！`;
        if (data.code == '-9') msg = `手机号格式不正确！`;
        if (data.code == '-10') msg = `用户名已存在！`;
        if (data.code == '-8') msg = `密码强度不满足要求！`;
        callback('fail');
        message.error(`新增或编辑失败，失败原因：${data?.mesg || data?.msg}`);
        console.error(`新增或编辑失败，失败原因：${data?.mesg || data?.msg}`, '接口名称： add 接口：portfolio-server/user/add');
      }
    },
    // 解锁账户
    *unLockUser({ payload, callback }, { call, put }) {
      const response = yield call(api.userManageNew.unLockUser, payload);
      if (response && response.success) {
        message.success(response.message || '解锁账户成功!');
        callback('success');
      } else {
        callback('fail');
        message.error(`解锁账户失败，失败原因：${response?.mesg || response?.msg}`);
        console.error(`解锁账户失败，失败原因：${response?.mesg || response?.msg}`, '接口名称： unLockUser 接口：usermanagement/user/unLockUser');
      }
    },
    // 解冻、冻结账户
    *updateActiveState({ payload, callback }, { call, put }) {
      const response = yield call(api.userManageNew.updateActiveState, payload);
      if (response && response.code == 0) {
        message.success('解冻/冻结账户成功！');
        callback('success');
      } else {
        callback('fail');
        message.error(`解冻/冻结账户失败！`);
      }
    },
    // 重置密码
    *resetPassWord({ payload, callback }, { call, put }) {
      const response = yield call(api.userManageNew.resetPassWord, payload);
      if (response && response.code == 0) {
        message.success('重置密码成功!');
        callback('success');
      } else {
        let msg = '重置失败！';
        if (response.code == '-1') msg = `重置失败！`;
        if (response.code == '-6') msg = `新老密码相同，重置失败！`;
        if (response.code == '-7') msg = `旧密码验证失败，重置失败！`;
        if (response.code == '-8') msg = `密码强度不满足要求，重置失败！`;
        callback('fail');
        message.error(msg);
      }
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
